from urllib import request, parse
import time
import datetime
import pytz
import hashlib
import common.modelAdminUser as modelAdminUser

def md5(str):
  '返回md5字符串'
  m = hashlib.md5(str.encode('utf-8')).hexdigest()
  return m

def getToken():
  '获取token'
  tz = pytz.timezone('Asia/Shanghai')
  #dt = datetime.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S")
  dt = datetime.datetime.now(tz).strftime("%Y%m%d%H")
  str="CEB*%!*Hx001"+dt
  str=md5(str)
  return str;

def getDateByUrl(url,parameter=[]):
  'HTTP提交或获取数据'
  
  
  arr=[('token',getToken())]
  
  #测试加的，上线删除
  #arr.append(('admin_id',1))
  #arr.append(('admin_pwd','cf9aea1dff4bbee155bf468b69e11544'))
  
  if len(parameter)>0:
    arr+=parameter
    
  req = request.Request(url)
  rt=""
  post_parame = parse.urlencode(arr)
  with request.urlopen(req,post_parame.encode('utf-8')) as f:
    data = f.read()
    rt=data.decode('utf-8')
  return rt

def getDateByUrlAndAdminId(url,from_req,parameter=[]):
  'HTTP提交或获取数据'
  
  
  arr=[('token',getToken())]
  
  #if not from_req.strip()=="":
  admin_id=modelAdminUser.getLoginUserId(from_req)
  arr.append(('admin_id',admin_id))
  admin_pwd=modelAdminUser.getLoginPwd(from_req)
  arr.append(('admin_pwd',admin_pwd))
  
  if len(parameter)>0:
    arr+=parameter
    
  req = request.Request(url)
  rt=""
  post_parame = parse.urlencode(arr)
  with request.urlopen(req,post_parame.encode('utf-8')) as f:
    data = f.read()
    rt=data.decode('utf-8')
  return rt